#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月17日

@author: Administrator
'''

from celery.task import task
from django.db import connection, transaction
from common.decorators.celery import task_exception_handler

@task
@task_exception_handler
def increase_like_count(model_class, ids, increase_count=1):
    u'''
    function: 增加like_count计数
    
    model_class - orm类名，如art.models.Art, tuce.models.Case, tuce.models.Photo等
    ids - 对应的表记录ids,  如[111,222]
    increase_count - 增加的计数，默认1
    '''
    if 'like_count' not in model_class._meta.get_all_field_names():
        return
    
    ids = list(set(ids))
    if len(ids) == 0:
        return
    
    cursor = connection.cursor()
    
    if len(ids) == 1:
        id = ids[0]
        sql = 'UPDATE ' + model_class._meta.db_table + ' SET like_count = (like_count + %(increase_count)s) WHERE id=%(id)s'''
        cursor.execute(sql, {'id': id, 'increase_count': increase_count})
    else:
        ids = [str(id) for id in ids]
        id_string = ','.join(ids)
        sql = 'UPDATE ' + model_class._meta.db_table + ' SET like_count = (like_count + %(increase_count)s) WHERE id IN (%(id_string)s)'''
        cursor.execute(sql, {'id_string': id_string, 'increase_count': increase_count})
    
    transaction.commit_unless_managed()
    cursor.close()
